package de.axone.wash;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;


public class FileWash extends DefaultWash {
	
	File file;
	
	public FileWash( File file ) {
		
		this.file = file;
	}
	
	public void read() throws IOException, CodingException {
		
		FileInputStream fileIn = new FileInputStream( file );
		
		String data = slurp( fileIn );
		
		deserialize( data );
	}
	
	public static String slurp( InputStream in )throws IOException {
		
	    StringBuilder out = new StringBuilder();
	    
	    byte[] b = new byte[4096];
	    
	    for (int n; (n = in.read(b)) != -1;) {
	        out.append(new String(b, 0, n));
	    }
	    return out.toString();
	}

	public void write() throws IOException, NotFoundException, WrongTypeException {

		FileWriter fw = new FileWriter( file );
		file.createNewFile();
		Set<String> field = this.getFieldNames();
		Object[] names = field.toArray();
		
		for( int i = 0; i < names.length; i++ ){
			String type = "";
			if( this.getType( names[i].toString() ) == Type.BOOLEAN ){
				type = "b"+String.valueOf( this.getBoolean( names[i].toString() ) );
			}else if( this.getType( names[i].toString() ) == Type.DATA ){
				type = "d"+String.valueOf( this.getData( names[i].toString() ) );
			}else if( this.getType( names[i].toString() ) == Type.FLOAT ){
				type = "f"+String.valueOf( this.getDouble( names[i].toString() ) );
			}else if( this.getType( names[i].toString() ) == Type.INTEGER ){
				type = "i"+String.valueOf( this.getLong( names[i].toString() ) );
			}else if( this.getType( names[i].toString() ) == Type.STRING ){
				type = "\""+this.getString( names[i].toString() );
			}
			fw.write( names[i].toString()+"="+type+"\n" );
			fw.flush();
		}
	}
}
